import React from "react";
import api from "../../until/index.js";
import { Input, Button, Table, message } from "antd";
import moment from "moment";
export default class UserAudio extends React.Component {
  formRef = React.createRef();
  constructor(props) {
    super(props);
    this.state = {
      text: "",
      dataList: [],
      colums: [
        {
          title: "#",
          align: "center",
          dataIndex: "id",
          key: "id",
          render: (text, record, index) => `${index + 1}`,
        },
        {
          title: "音频",
          align: "center",
          dataIndex: "audio",
          key: "audio",
          render: (text) => <audio controls src={text}></audio>,
        },
        {
          title: "添加时间",
          align: "center",
          dataIndex: "tiem",
          key: "tiem",
          render: (val) => (
            <span>
              {val
                ? moment(Number(val)).format("YYYY-MM-DD HH:mm:ss")
                : moment("2020-6-1 00:00:00").format("YYYY-MM-DD HH:mm:ss")}
            </span>
          ),
        },
      ],
    };
  }
  async componentDidMount() {
    let token = sessionStorage.getItem("token");
    let res = await api.getToken({ token });
    //console.log(res.data.message.username)
    let data = {
      user: JSON.stringify(res.data.message.username),
    };
    let result = await api.getuserlist(data);
    sessionStorage.setItem("userId", result.data.message[0].id);
    let List = await api.getUserAudio({ userid: result.data.message[0].id });
    this.setState({
      dataList: List.data.message.reverse(),
    });
  }
  //输入框监听
  onChange = (e) => {
    // console.log(e)
    this.setState({
      [e.target.name]: e.target.value,
    });
  };
  getadd = async () => {
    if (!this.state.text) {
      message.warning("请输入要合成的文字");
      return false;
    }
    // console.log(this.state.text)
    let result = await api.getAudio({ text: this.state.text });
    let data = {
      audio: result.data.data,
      tiem: +new Date() + "",
      userid: sessionStorage.getItem("userId"),
    };
    let res = await api.addAudio(data);
    if (res.data.err_code == 0) {
      //eslint-disable-line
      message.success("添加成功");
      this.componentDidMount();
    }
  };
  render() {
    const { colums, dataList } = this.state;
    return (
      <div>
        <div>
          <Input
            name="text"
            allowClear
            onChange={this.onChange}
            style={{ width: "250px", margin: "0 20px 20px 0" }}
            placeholder="请输入要合成的文字"
          ></Input>
          <Button type="primary" onClick={this.getadd}>
            合成
          </Button>
        </div>
        <Table
          columns={colums}
          dataSource={dataList}
          bordered
          bottomLeft
          rowKey={(record) => record.id}
        ></Table>
      </div>
    );
  }
}
